package org.onion.pattern.event.springboot.rocketmq.consume;


import org.onion.pattern.event.consumer.EventConsumeHandler;
import org.onion.pattern.event.consumer.ExternalEventInfo;
import org.onion.pattern.event.spring.consumer.PublishSpringApplicationEventHandler;
import org.onion.pattern.event.springboot.rocketmq.annotation.RocketMQConsumerGroup;
import org.onion.pattern.event.springboot.rocketmq.consume.distribute.RocketMQApplicationEvent;
import org.onion.pattern.event.springboot.rocketmq.config.RocketMessageMetadata;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.context.ApplicationContext;

import java.util.Objects;


public class RocketMQMQEventConsumeHandler extends PublishSpringApplicationEventHandler implements EventConsumeHandler {

    private final Object   consumerGroup;
    private final Class<?> consumerGroupType;

    public RocketMQMQEventConsumeHandler(Object consumerGroup, ApplicationContext applicationContext) {
        this.consumerGroup = Objects.requireNonNull(consumerGroup);
        this.applicationContext = Objects.requireNonNull(applicationContext);
        Objects.requireNonNull(consumerGroup);
        consumerGroupType = AopProxyUtils.ultimateTargetClass(consumerGroup);
        Objects.requireNonNull(consumerGroupType.getAnnotation(RocketMQConsumerGroup.class), "必须是RocketMQConsumerGroup");
    }

    @Override
    public Class<?> consumerGroupClass() {
        return consumerGroupType;
    }

    @Override
    protected final Object buildPublishEvent(ExternalEventInfo eventInfo, Object metadata) {
        RocketMessageMetadata metadata_ = (RocketMessageMetadata) metadata;
        return new RocketMQApplicationEvent(eventInfo.getPayload(), metadata_);
    }

    @Override
    public Object consumerGroup() {
        return this.consumerGroup;
    }


}
